import { PlatformEnum } from '@/utils/enum';
import appConfig from '../appConfig';
import request from '../request';
import Taro from '@tarojs/taro';
/**
 * 将微信公共平台获取的code转换成sessionKey
 *
 * @param data 包含code和businessMerchantAppConfigId的对象
 * @returns 返回请求结果
 */
async function weChatPubCode2SessionV1(code: string): Promise<{ accessToken: string }> {
    return request({
        url: '/api/WeChatPub/Login',
        method: 'post',
        data: {
            code,
            merchantId: appConfig.merchantId,
            smallAppId: appConfig.smallAppId,
            appConfigId: appConfig.appConfigId,
        },
    });
    // return request({ url: '/api/WeChatPub/Code2SessionV1', data })
}
const auth: AppConfigType['auth'] = async (oldToken) => {
    const { appPlatformType } = appConfig;
    switch (appPlatformType) {
        case PlatformEnum.WeChatPub: {
            if (process.env.NODE_ENV === 'development') {
                if (oldToken) return oldToken;
                return false;
            }
            if (oldToken) return oldToken;
            const url = new URL(window.location.href);
            const { searchParams } = url;
            const code = searchParams.get('code');
            // 公众号 静默授权
            if (!code) {
                window.location.href =
                    'http://open.weixin.qq.com/connect/oauth2/authorize?' +
                    `appid=${appConfig.appId}` +
                    `&redirect_uri=${encodeURIComponent(`${window.location.href}`)}` +
                    `&response_type=code` +
                    `&scope=snsapi_userinfo` +
                    `#wechat_redirect`;
                return false;
            } else {
                const { accessToken } = await weChatPubCode2SessionV1(code);
                Taro.setStorageSync('token', accessToken);
                searchParams.delete('code');
                searchParams.delete('state');
                window.history.replaceState(window.history.state, '', url.href);
                return accessToken !== undefined ? accessToken : false;
            }
        }
        case PlatformEnum.H5: {
            if (oldToken) return oldToken;
            // H5 （普通浏览器环境）则手动登录
            return false;
        }
        default:
            return oldToken ? oldToken : false;
    }
};

export default auth;
